package com.module.shici.ui;

import android.app.AlertDialog;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.fenghuajueli.libbasecoreui.utils.MyStatusBarUtils;
import com.fenghuajueli.libbasecoreui.utils.QuickClickUtils;
import com.module.shici.R;
import com.module.shici.adapter.YinPinListRvAdapter;
import com.module.shici.bean.StoryBean;
import com.module.shici.bean.YinpinData;
import com.module.shici.databinding.ModuleShiciActivityVoiceBinding;
import com.module.shici.room.Music;
import com.module.shici.room.MusicDao;
import com.module.shici.room.MusicDataBase;
import com.module.shici.room.entity.Collect;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class VoiceActivity extends AppCompatActivity implements View.OnClickListener {

    ModuleShiciActivityVoiceBinding binding;
    private boolean yinpinFalg = false;
    private List<Music> musicList;
    private int id = 0;
    private String title = "故事";
    YinpinData yinpinData = new YinpinData();

    //播放
    private MediaPlayer mediaPlayer;
    private SimpleDateFormat mFormat;
    private Timer timer;
    private boolean flag = true, loopFlag = true;//flag用来判断是否播放,loopFlag用了判断是否循环播放
    //收藏
    private Boolean collectFlag = false;//true 为收藏，false 为取消收藏
    private Boolean collectSQLFlag = false;//true 为数据库已有，false 为数据库没有
    private MusicDao musicDao = MusicDataBase.getInstance().getMusicDao();
    //播放列表
    private TextView yinpin_list_title;
    private RecyclerView yinpin_list_rv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ModuleShiciActivityVoiceBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        MyStatusBarUtils.setStatusBar(this,"#00000000");
        Intent intent = getIntent();
        id = intent.getIntExtra("ID",0);
        switch (intent.getIntExtra("imgType",1)){
            case 1:
                musicList = yinpinData.getCollectList();
                title = "喜欢";
                break;
            case 2:
                musicList = yinpinData.getStoryList();
                title = "故事";
                break;
            case 3:
                musicList = yinpinData.getErgeList();
                title = "晨起";
                break;
            case 4:
                musicList = yinpinData.getPianoList();
                title = "哄睡";
                break;
        }
        //初始化数据
        initYinPinData();
        //初始化播放
        initMediaPlayer();
        //初始化seekBar
        initSeekBar();
        binding.yinpinListBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }


    private void initYinPinData() {
        //获取标题
        binding.yinpinTitle.setText(musicList.get(id).getTitle());
        //获取二级标题
        binding.yinpinChaper.setText(musicList.get(id).getChaper());

        binding.yinpinLoop.setOnClickListener(this);
        binding.yinpinUp.setOnClickListener(this);
        binding.yinpinPlay.setOnClickListener(this);
        binding.yinpinNext.setOnClickListener(this);
        binding.yinpinList.setOnClickListener(this);
        binding.yinpinCollect.setOnClickListener(this);

        if (musicDao.queryCollectByTitle(musicList.get(id).getChaper()).size() != 0) {
            collectFlag = true;
            collectSQLFlag = true;
            binding.yinpinCollect.setImageResource(R.mipmap.module_shici_yinpin_icon_like_sel);
        } else {
            collectFlag = false;
            collectSQLFlag = false;
            binding.yinpinCollect.setImageResource(R.mipmap.module_shici_yinpin_icon_like_nor);
        }
    }

    //seekbar 的监听事件
    private void initSeekBar() {
        binding.yinpinSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            //滚动条发生变化时触发
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                binding.yinpinStartTime.setText(mFormat.format(seekBar.getProgress()));
            }

            @Override
            //滚动条按下时触发
            public void onStartTrackingTouch(SeekBar seekBar) {
//                binding.musicPlaySatrtTime.setText(mFormat.format(seekBar.getProgress()));
            }

            @Override
            //滚动条松开时触发
            public void onStopTrackingTouch(SeekBar seekBar) {
                //播放到滚动条相对应的位置
                mediaPlayer.seekTo(seekBar.getProgress());
                binding.yinpinStartTime.setText(mFormat.format(mediaPlayer.getCurrentPosition()));
            }
        });
    }

    private void initMediaPlayer() {
     /*   if (id > 0) {
            if (PublicFunction.checkCanNext()) {
                initPay();
            }
        } else {
            initPay();
        }*/

        initPay();
    }

    private void initPay() {
        //创建播放时间格式化工具
        mFormat = new SimpleDateFormat("mm:ss");
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        //设置播放文件
        try {
            mediaPlayer.setDataSource(musicList.get(id).getOss_file());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 通过异步的方式装载媒体资源
        mediaPlayer.prepareAsync();
        //装载流媒体完毕的时候回调。
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                //开始播放
                mediaPlayer.start();
                //getDuration() ：得到文件的时间
                binding.yinpinLastTime.setText(mFormat.format(mediaPlayer.getDuration()));
                LogUtils.d(mediaPlayer.getDuration());
                //设置拖动条的最大值
                binding.yinpinSeekbar.setMax(mediaPlayer.getDuration());
                isTimer();
            }
        });
        //网络流媒体播放结束时回调
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (loopFlag) {
                    //单曲循环
                    clear();
                    initMediaPlayer();
                } else {
                    //下一首
                    if (id >= musicList.size() - 1) {
                        id = -1;
                    }
                    id += 1;
                    clear();
                    initMediaPlayer();
                }
            }
        });
    }

    //计时器
    private void isTimer() {
        if (timer == null) {
            // 创建一个Timer调度器
            timer = new Timer();
            // 设置0秒后开始执行muiscTimer任务  每1秒执行一次
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //getCurrentPosition( )：得到当前的播放位置
                    try {
                        if (mediaPlayer!=null){
                            binding.yinpinSeekbar.setProgress(mediaPlayer.getCurrentPosition());
                        }
                    }catch (IllegalStateException e){

                    }
                }
            }, 0, 1000);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() != R.id.yinpin_play){
            //防抖
            if (QuickClickUtils.isFastClick()) {
                return;
            }
        }
        if (v.getId() == R.id.yinpin_loop){
            //是否循环
            loopFlag = !loopFlag;
            if (loopFlag) {
                binding.yinpinLoop.setImageResource(R.mipmap.module_shici_yinpin_icon_xunhuan);
                ToastUtils.showShort("已切换为循环播放");
            } else {
                binding.yinpinLoop.setImageResource(R.mipmap.module_shici_yinpin_icon_liebiaoxunhuan);
                ToastUtils.showShort("已切换为列表播放");
            }
        }else if (v.getId() == R.id.yinpin_up){
            //上一首
            //当到达第一首时，再上一首就变成最后一首
            if (id <= 0) {
                id = musicList.size();
            }
            id -= 1;
            clear();
            initMediaPlayer();
        }else if (v.getId() == R.id.yinpin_play){
            //播放/暂停
            flag = !flag;
            //是否播放
            isplay(flag);
        }else if (v.getId() == R.id.yinpin_next){
            //下一首
            if (id >= musicList.size() - 1) {
                id = -1;
            }
            id += 1;
            clear();
            initMediaPlayer();
        }else if (v.getId() == R.id.yinpin_list){
            //播放列表
            yinpinListDialog();
        }else if (v.getId() == R.id.yinpin_collect){
            //是否收藏
            collectFlag = !collectFlag;
            if (collectFlag) {
                binding.yinpinCollect.setImageResource(R.mipmap.module_shici_yinpin_icon_like_sel);
                ToastUtils.showShort("收藏成功");
            } else {
                binding.yinpinCollect.setImageResource(R.mipmap.module_shici_yinpin_icon_like_nor);
                ToastUtils.showShort("取消收藏");
            }
            collect();
        }
    }

    private void isplay(boolean flag) {
        if (mediaPlayer == null) {
            binding.yinpinPlay.setImageResource(R.mipmap.module_shici_yinpin_icon_bf);
            return;
        }
        if (flag) {
            binding.yinpinPlay.setImageResource(R.mipmap.module_shici_yinpin_icon_zt);
            mediaPlayer.start();
            isTimer();
        } else {
            binding.yinpinPlay.setImageResource(R.mipmap.module_shici_yinpin_icon_bf);
            mediaPlayer.pause();
            if (timer!=null){
                timer.cancel();
                timer = null;
            }
        }
    }

    //播放列表对话框
    private void yinpinListDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(VoiceActivity.this);
        View view = View.inflate(VoiceActivity.this, R.layout.module_shici_dialog_yin_pin_list,null);
        builder.setView(view);
//        builder.setCancelable(false);
        AlertDialog dialog = builder.create();
        //设置对话框在屏幕的下方
//        dialog.getWindow().getAttributes().gravity = Gravity.BOTTOM;
        dialog.show();
        //需要在设置完布局之后调用
        //因为背景默认有padding值，所以不能全屏
        dialog.getWindow().setBackgroundDrawable(null);
        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        view.findViewById(R.id.yinpin_list_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        yinpin_list_title= view.findViewById(R.id.yinpin_list_title);
        yinpin_list_title.setText(title);
        yinpin_list_rv= view.findViewById(R.id.yinpin_list_rv);
        LinearLayoutManager linearLayout = new LinearLayoutManager(VoiceActivity.this);
        yinpin_list_rv.setLayoutManager(linearLayout);
        YinPinListRvAdapter yinPinListRvAdapter = new YinPinListRvAdapter(musicList,id);
        yinpin_list_rv.setAdapter(yinPinListRvAdapter);
        yinPinListRvAdapter.getYinPinListPosition(new YinPinListRvAdapter.YinPinListListener() {
            @Override
            public void setYinPinListPosition(int position) {
          /*      if (position >0) {
                    if (PublicFunction.checkCanNext()) {
                        id = position;
                        clear();
                        initMediaPlayer();
                    }
                } else {
                    id = position;
                    clear();
                    initMediaPlayer();
                }*/


                id = position;
                clear();
                initMediaPlayer();
            }
        });
    }

    //回收资源
    private void clear() {
        //页面销毁时，回收资源
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        //清空定时器
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        //初始化数据
        if (musicList != null) {
            binding.yinpinTitle.setText(musicList.get(id).getTitle());
            binding.yinpinChaper.setText(musicList.get(id).getChaper());
            binding.yinpinSeekbar.setProgress(0);
            flag = true;
            binding.yinpinPlay.setImageResource(R.mipmap.module_shici_yinpin_icon_zt);

            if (musicDao.queryCollectByTitle(musicList.get(id).getChaper()).size() != 0) {
                collectFlag = true;
                collectSQLFlag = true;
                binding.yinpinCollect.setImageResource(R.mipmap.module_shici_yinpin_icon_like_sel);
            } else {
                collectFlag = false;
                collectSQLFlag = false;
                binding.yinpinCollect.setImageResource(R.mipmap.module_shici_yinpin_icon_like_nor);
            }
        }

    }
    //收藏
    public void collect(){
        int img = StoryBean.storyGSImg[id%4];
        if (title.equals("故事")){
            img = StoryBean.storyGSImg[id%4];
        }else if (title.equals("晨起")){
            img = StoryBean.storyEGImg[id%4];
        }else if (title.equals("哄睡")){
            img = StoryBean.storyTHImg[id%4];
        }
        //判断是否点了收藏
        if (collectFlag) {
            //如果数据库中没有，则添加
            if (!collectSQLFlag){
                //收藏
                musicDao.InsertCollect(new Collect(img, musicList.get(id).getChaper(), musicList.get(id).getOss_file()));
                collectSQLFlag = true;
            }
        } else {
            if (collectSQLFlag){
                //取消收藏，从数据库中删除
                musicDao.deleteCollect(musicList.get(id).getChaper());
                collectSQLFlag = false;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //页面销毁时，回收资源
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (timer !=null){
            timer.cancel();
            timer = null;
        }
    }
}